/**
 * FileName: AdjacencyListsGraph.c
 * ---------------------------------------------------------------------------------------------------------------------
 * Program 17.6 Graph ADT implementation (adjacency lists)
 * ---------------------------------------------------------------------------------------------------------------------
 * This implementation of the interface in Program 17.1 uses an array of lists, one corresponding to each vertex.
 * An edge `v-w` is represented by a node for w on list v and a node for v on list w.
 *
 * As in Program 17.3, `GRAPHedges` puts just one of the two representations of each edge into the output array.
 *
 * Implementations of `GRAPHcopy`, `GRAPHdestroy`, and `GRAPHremoveE` are omitted.
 *
 * The `GRAPHinsertE` code keeps insertion time constant by not checking for duplicate edges.
 *
 *
 */
#include <stdio.h>
#include <stdlib.h>

//边相关
typedef struct {
    int v;
    int w;
}
Edge;

//顶点相关
typedef struct node* link;
struct node {
    int v;
    link next;
};

//图相关
typedef struct graph *Graph;
struct graph {
    int V;
    int E;
    link* adj;
};

//辅助函数声明
link NEW(int, link);
Edge EDGE(int, int);
void GRAPHshow(Graph);

//图操作声明
Graph GRAPHinit(int);
void GRAPHinsertE(Graph, Edge);
void GRAPHremoveE(Graph, Edge);
int GRAPHedges(Edge [], Graph);
Graph GRAPHcopy(Graph);
void GRAPHdestroy(Graph);

//辅助函数实现
link NEW(int v, link next) {
    link x = (link) malloc(sizeof(*x));
    x->v = v;
    x->next = next;
    return x;
}

Edge EDGE(int v, int w) {
    Edge edge;
    edge.v = v;
    edge.w = w;
    return edge;
}

void GRAPHshow(Graph G) {
    printf("%d vertices, %d edges\n", G->V, G->E);
    int v;
    link t;
    for (v = 0; v < G->V; v++) {
        printf("%2d:", v);
        for (t = G->adj[v]; t != NULL; t = t->next) {
            printf(" %2d", t->v);
        }
        printf("\n");
    }
}

//图操作函数实现
Graph GRAPHinit(int V) {
    int v;
    Graph G = malloc(sizeof(*G));
    G->V = V;
    G->E = 0;
    G->adj = (link*) malloc(V * sizeof(link));
    for (v = 0; v < V; v++) {
        G->adj[v] = NULL;
    }
    return G;
}

void GRAPHinsertE(Graph G, Edge e) {
    int v = e.v;
    int w = e.w;
    G->adj[v] = NEW(w, G->adj[v]);
    G->adj[w] = NEW(v, G->adj[w]);
    G->E++;
}

void GRAPHremoveE(Graph G, Edge e) {
    //TODO
}
int GRAPHedges(Edge a[], Graph G) {
    int E = 0;
    int v;
    link t;
    for (v = 0; v < G->V; v++) {
        for (t = G->adj[v]; t != NULL; t = t->next) {
            if (v < t->v) {
                a[E++] = EDGE(v, t->v);
            }
        }
    }

    return E;
}
Graph GRAPHcopy(Graph G) {
    //TODO
}
void GRAPHdestroy(Graph G) {
    //TODO
}